<?php

namespace app\api\controller;
use think\Controller;
use alidayu\TopClient;
use alidayu\AlibabaAliqinFcSmsNumSendRequest;
use data\Json;
use think\Cache;
/**
 * 接口控制器基类
 */
class Base extends Controller
{
    public function _empty($name)
    {
        // 空方法操作
        return Json::json_send(4);
    }

     /**
     * 手机验证码
     */
    public function sms()
    {
        $validate = new Validate([
            //['param','require|array','参数必填|参数必须为数组'],
            ['mobile','require|/1[34578]{1}\d{9}$/','手机号错误|手机号错误'],
        ]);
        
        $mobile = $data['mobile'] = input("mobile");

        if (!$validate->check($data)) {
            return $this->sendError(400, $validate->getError());
        }

        $user = Db::name($this->member_model)->field("id")->where('mobile',$mobile)->find();
        if(!$user)
        {
            $user = Db::name($this->butler_model)->field("id")->where(['is_deleted'=>0,'mobile'=>$mobile])->find();
        }

        if(!$user)
        {
           //Log::error('登录获取短信验证码---用户不存在');
           return $this->sendError(407);
        }
        
        return $this->sendSMS($mobile);
    }

    // 发送短信验证码
    public function sendSMS($mobile,$prefix='')
    {
        $number = randCode();
        $product="圈子";
        $c = new TopClient();
        $c->appkey = config('aliyun_SMS.appkey');
        $c->secretKey = config('aliyun_SMS.secretKey');
        $req = new AlibabaAliqinFcSmsNumSendRequest;
                
        $req->setSmsType("normal");
        $req->setSmsFreeSignName(config('aliyun_SMS.signName'));
        $req->setSmsParam("{\"code\":\"$number\",\"product\":\"$product\"}");
       // $req->setSmsParam("{\"customer\":\"$number\",\"product\":\"$product\"}");
        $req->setRecNum($mobile);
        $req->setSmsTemplateCode(config('aliyun_SMS.templateCode'));
        
        $resp = $c->execute($req);
        if(isset($resp->code))
        {
            return Json::json_send(401);
        }
        
        if($resp->result->err_code == 0)
        {
            // 将发送的短信验证码放到缓存中，5分钟过期
            Cache::set($prefix.$mobile, $number, '300');
            return Json::json_send(0,"短信发送成功");
        }
        else
        {
            return Json::json_send(402);
        }
    }
}
